package com.toocms.sample.parser;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Response;
import rxhttp.wrapper.annotation.Parser;
import rxhttp.wrapper.exception.ParseException;
import rxhttp.wrapper.parse.TypeParser;
import rxhttp.wrapper.utils.Converter;

/**
 * @Description:
 * @Author: Zero
 * @CreateDate: 2021/12/24 14:58
 * @UpdateUser:
 * @UpdateDate: 2021/12/24 14:58
 * @UpdateRemark:
 * @Version: 1.0
 */

@Parser(name = "TestResponse")
public class TestParser<T> extends TypeParser<T> {

    protected TestParser() {
        super();
    }

    public TestParser(Type type) {
        super(type);
    }

    @Override
    public T onParse(@NonNull Response response) throws IOException {
        TestResponse<T> data = Converter.convertTo(response, TestResponse.class, types);  //这里的types就是自定义Response<T>里面的泛型类型
        T t = data.getData(); //获取data字段
        if (!data.getFlag().equals("success") || t == null) {//这里假设code不等于200，代表数据不正确，抛出异常
            throw new ParseException(data.getFlag(), data.getMessage(), response);
        }
        return t;


//        final Type type = ParameterizedTypeImpl.get(TooCMSResponse.class, String.class);
//        TooCMSResponse<String> tooCMSResponse = Converter.convert(response, type);
//
//        if (TextUtils.equals(tooCMSResponse.getFlag(), "error"))
//            throw new LogicException(tooCMSResponse.getFlag(), tooCMSResponse.getMessage(), tooCMSResponse.getData(), response);
//
//        T t = GsonUtil.getObject(tooCMSResponse.getData(), types);
//
//        if (t == null || (mType == String.class && (StringUtils.equals(t.toString(), "{}") || StringUtils.equals(t.toString(), "[]")))) {
//            t = (T) tooCMSResponse.getMessage();
//        }
//        return t;
    }
}
